package com.chen.holiday.infrastructure.dao;

import com.alibaba.fastjson.JSONObject;
import com.chen.holiday.domain.holiday.Holiday;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.time.LocalDate;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author 陈浩
 * @date 2021/5/17 10:45
 */
public class HolidayDao {

    final String url = "http://timor.tech/api/holiday/year/";

    public HashMap<LocalDate, Holiday> getHoliday() throws Exception {
        ArrayList<Holiday> holidayList = getHolidayList();
        if (holidayList == null) {
            throw new Exception("查找节假日接口出错");
        }
        return new HashMap<>(holidayList.stream().collect(Collectors.toMap(Holiday::getDate, Function.identity())));

    }


    private ArrayList<Holiday> getHolidayList() {
        Map requestHoliday = requestHoliday();
        Integer code = (Integer) requestHoliday.get("code");
        ArrayList<Holiday> rawInfoList = new ArrayList<>();
        if (code == 0){
            JSONObject holiday = (JSONObject)requestHoliday.get("holiday");
            Set<Map.Entry<String, Object>> entries = holiday.entrySet();
            for (Map.Entry<String, Object> entry : entries) {
                String key = entry.getKey();
                Object value = entry.getValue();
                Holiday object = JSONObject.parseObject(JSONObject.toJSONString(value), Holiday.class);
                rawInfoList.add(object);
            }
            return rawInfoList;
        }
        return null;
    }

    /**
     * 请求接口获取当年的节假日和补班数据
     * @return
     */
    private Map requestHoliday() {
        OkHttpClient client = new OkHttpClient();
        Response response;
        //解密数据
        String rsa = null;
        Request request = new Request.Builder()
                .url(url)
                .get()
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        try {
            response = client.newCall(request).execute();
            rsa = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JSONObject.parseObject(rsa, Map.class);
    }

}
